package com.elitel.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.jsoup.helper.DataUtil;

import com.elitel.frame.main.entity.CfgDb;
import com.elitel.frame.main.entity.vo.ServerStatistics;
import com.google.gson.Gson;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class FileWriterUtil {
	

	public static String savefile = "E:\\";
	
	/**
	 * 向txt文件中写入数据
	 * @param content
	 */
	public static void saveAsFileWriter(String sessionID,String content) {
		//content = content.replaceAll("\t", " ");
		JSONObject jsonObject=JSONObject.fromObject(content);
		ServerStatistics stu=(ServerStatistics)JSONObject.toBean(jsonObject, ServerStatistics.class);
		String serverString = "time="+DateUtilFormat.dataToString(new Date())+";servername="+stu.getServerName()+";serverSql="+stu.getSql();
		Gson gson = new Gson();
		File file = new File(savefile+sessionID+".txt");
//		if (file.exists()) {
//			file.delete();
//		}
		FileWriter fwriter = null;
		try {
			fwriter = new FileWriter(savefile+sessionID+".txt");
			Map<String, Object> map = new HashMap<>();
			map.put(DateUtilFormat.dataToString(new Date()), content);
			fwriter.write(serverString);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				fwriter.flush();
				fwriter.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
	/**
	 * 从txt文件中读取数据
	 * @param file
	 * @return
	 */
    public static String txt2String(String sessionID){
    	File file = new File(savefile+sessionID+".txt");
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
    
    public static String montage(String serverID,String date,String key,List<?> list){
//    	Gson gson = new Gson();
//    	System.out.println(gson.toJson(object));
    	String sqlsql = JSONArray.fromObject(list).toString();
    	return "time="+date+";serverID="+serverID+";key+"+key+";data="+JSONArray.fromObject(list);
    } 
    
}
